/**
 *
 * @param obj1
 * @param obj2
 */
Raphael.fn.connection = function (obj1, obj2, line, bg) {
    if (obj1.line && obj1.from && obj1.to) {
        line = obj1;
        obj1 = line.from;
        obj2 = line.to;
    }
    var bb1 = obj1.getBBox(),
        bb2 = obj2.getBBox(),
        p = [{x: bb1.x + bb1.width / 2, y: bb1.y - 1},
            {x: bb1.x + bb1.width / 2, y: bb1.y + bb1.height + 1},
            {x: bb1.x - 1, y: bb1.y + bb1.height / 2},
            {x: bb1.x + bb1.width + 1, y: bb1.y + bb1.height / 2},
            {x: bb2.x + bb2.width / 2, y: bb2.y - 1},
            {x: bb2.x + bb2.width / 2, y: bb2.y + bb2.height + 1},
            {x: bb2.x - 1, y: bb2.y + bb2.height / 2},
            {x: bb2.x + bb2.width + 1, y: bb2.y + bb2.height / 2}],
        d = {}, dis = [];
    for (var i = 0; i < 4; i++) {
        for (var j = 4; j < 8; j++) {
            var dx = Math.abs(p[i].x - p[j].x),
                dy = Math.abs(p[i].y - p[j].y);
            if ((i == j - 4) || (((i != 3 && j != 6) || p[i].x < p[j].x) && ((i != 2 && j != 7) || p[i].x > p[j].x) && ((i != 0 && j != 5) || p[i].y > p[j].y) && ((i != 1 && j != 4) || p[i].y < p[j].y))) {
                dis.push(dx + dy);
                d[dis[dis.length - 1]] = [i, j];
            }
        }
    }
    if (dis.length == 0) {
        var res = [0, 4];
    } else {
        res = d[Math.min.apply(Math, dis)];
    }
    var x1 = p[res[0]].x,
        y1 = p[res[0]].y,
        x4 = p[res[1]].x,
        y4 = p[res[1]].y;
    dx = Math.max(Math.abs(x1 - x4) / 2, 10);
    dy = Math.max(Math.abs(y1 - y4) / 2, 10);
    var x2 = [x1, x1, x1 - dx, x1 + dx][res[0]].toFixed(3),
        y2 = [y1 - dy, y1 + dy, y1, y1][res[0]].toFixed(3),
        x3 = [0, 0, 0, 0, x4, x4, x4 - dx, x4 + dx][res[1]].toFixed(3),
        y3 = [0, 0, 0, 0, y1 + dy, y1 - dy, y4, y4][res[1]].toFixed(3);
    var path = ["M", x1.toFixed(3), y1.toFixed(3), "C", x2, y2, x3, y3, x4.toFixed(3), y4.toFixed(3)].join(",");
    if (line && line.line) {
        line.bg && line.bg.attr({path: path});
        line.line.attr({path: path});
    } else {
        var color = typeof line == "string" ? line : "#000";

        return {
            bg: bg && bg.split && this.path(path).attr({stroke: bg.split("|")[0], fill: "none", "stroke-width": bg.split("|")[1] || 3}),
            line: this.path(path).attr({'arrow-end':'classic-wide-long', "stroke-width": 2, stroke: color, fill: "none"}),
            from: obj1,
            to: obj2
        };
    }
};


function drawRects(divContainer,svgContainer,status ,leftOffset,topOffset) {
    var connections = []; //节点之间的连线
    var shapes = []; //节点（矩形）

    var nodes = $("#"+divContainer+" div"); //节点填充的div

    //计算画布大小
    var rows = 0; //整个图形有多少行
    var cols = 0; //整个图形有多少列
    var rowHeight = 50; //每行高度
    var colWidth = 110; //每列宽度
    var pointWidth = 24; //节点宽度
    var pointHeight = 24;//节点高度

    leftOffset = parseInt(leftOffset); //所有div的初始left偏移量
    topOffset = parseInt(topOffset); //所有div的初始top偏移量
    var colOfMaxRows; //行数最多的列
    var colPoints = []; // 每列的节点ID
    var points = []; //组装所有的节点

    for (var i = 0; i < nodes.length; i++) {
        var currentPointId = $(nodes[i]).attr("id");
        var currentPoint = {};

        currentPoint.nextPoints = $(nodes[i]).attr("next").split(",");
        currentPoint.prevPoints = [];
        currentPoint.id = currentPointId;
        currentPoint.index = i;
        points[currentPoint.id] = currentPoint;

        if(currentPointId != 0 && currentPointId != 999) {
            var colNO = parseInt(currentPoint.id.substring(0, 2)) - 9;
            if (cols < colNO) {
                cols = colNO;
            }
            if(colPoints[colNO] == undefined) {
                colPoints[colNO] = currentPointId;
            } else {
                colPoints[colNO] = colPoints[colNO] + "," + currentPointId;
            }
        }
    }
    colPoints[0] = "0";
    colPoints[colPoints.length] = "999";
    cols = cols + 2;

    //查找每个节点的上一节点ID
    for (var currentPointId in points) {
        var currentPoint = points[currentPointId];
        for(var j = 0; j < currentPoint.nextPoints.length; j++) {
            var nextPointId = currentPoint.nextPoints[j];
            var nextPoint = points[nextPointId];
            if(nextPoint != undefined && nextPoint != null) {
                nextPoint.prevPoints[nextPoint.prevPoints.length] = currentPointId;
            }
        }
    }

    //计算最大行数
    for (var colNO in colPoints) {
        if(rows < colPoints[colNO].split(",").length) {
            rows = colPoints[colNO].split(",").length;
            colOfMaxRows = parseInt(colNO);
        }
    }


    //计算画布的宽度和高度
    var raphaelWidth = (cols) * colWidth;
    var raphaelHeight = (rows) * rowHeight;

    //每次置空svgContainer中的svg数据
    $("#"+svgContainer).html("");

    var r = Raphael(svgContainer, raphaelWidth, raphaelHeight);


    //画行数最多的那一列的图形
    var pointIds = colPoints[colOfMaxRows].split(",");
    for(var j = 0; j < pointIds.length; j++) {
        var currentPoint = points[pointIds[j]];
        //节点的X坐标
        var pointX = (colOfMaxRows * colWidth) + colWidth/2 - pointWidth/2;
        //节点的Y坐标
        var pointY = (j * rowHeight) + rowHeight/2 - pointHeight/2;
        //保存当前节点的坐标
        currentPoint.x = pointX;
        currentPoint.y = pointY;

        shapes[currentPoint.index] = r.rect(pointX, pointY, pointWidth, pointHeight, pointWidth/2);
        //div的offset
        $(nodes[currentPoint.index]).offset({ left:pointX + leftOffset, top:pointY + topOffset -$("#"+divContainer).parent().scrollTop()});
        $(nodes[currentPoint.index]).css("z-index", "999");
    }

    //画行数最多的那一列前面的图形
    for (var i = colOfMaxRows - 1; i > -1; i--) {
        var pointIds = colPoints[i].split(",");
        for(var j = 0; j < pointIds.length; j++) {
            var currentPoint = points[pointIds[j]];
            //当前节点的X坐标
            var pointX = (i * colWidth) + colWidth/2 - pointWidth/2;
            //计算当前节点的Y坐标，查找当前节点所有next的最大与最小Y坐标，然后Y坐标
            var maxH = 0;
            var minH = 10000;
            var nextPoints = currentPoint.nextPoints;
            for(var k in nextPoints) {
                var tempPoint = points[nextPoints[k]];
                if(tempPoint.y >= maxH) {
                    maxH = tempPoint.y;
                }

                if(tempPoint.y <= minH) {
                    minH = tempPoint.y;
                }
            }

            var pointY = minH + (maxH - minH)/2;
            //保存当前节点的坐标
            currentPoint.x = pointX;
            currentPoint.y = pointY;

            shapes[currentPoint.index] = r.rect(pointX, pointY, pointWidth, pointHeight, pointWidth/2);
            //div的offset

            $(nodes[currentPoint.index]).offset({ left:pointX + leftOffset, top:pointY + topOffset -$("#"+divContainer).parent().scrollTop()});
            $(nodes[currentPoint.index]).css("z-index", "999");
        }
    }
    //画行数最多的那一列后面的图形
    for (var i = colOfMaxRows + 1; i < cols; i++) {
        var pointIds = colPoints[i].split(",");
        for(var j = 0; j < pointIds.length; j++) {
            var currentPoint = points[pointIds[j]];
            //当前节点的X坐标
            var pointX = (i * colWidth) + colWidth/2 - pointWidth/2;
            //计算当前节点的Y坐标，查找当前节点所有next的最大与最小Y坐标，然后Y坐标
            var maxH = 0;
            var minH = 10000;
            var prevPoints = currentPoint.prevPoints;
            for(var k in prevPoints) {
                var tempPoint = points[prevPoints[k]];
                if(tempPoint.y >= maxH) {
                    maxH = tempPoint.y;
                }

                if(tempPoint.y <= minH) {
                    minH = tempPoint.y;
                }
            }

            var pointY = minH + (maxH - minH)/2;
            currentPoint.x = pointX;
            currentPoint.y = pointY;

            shapes[currentPoint.index] = r.rect(pointX, pointY, pointWidth, pointHeight, pointWidth/2);
            //div的offset
            $(nodes[currentPoint.index]).offset({ left:pointX + leftOffset, top:pointY + topOffset-$("#"+divContainer).parent().scrollTop() });
            $(nodes[currentPoint.index]).css("z-index", "999");
        }
    }


    for (var i = 0, ii = shapes.length; i < ii; i++) {
        //设置流程跟踪图的背景颜色
        var color = $(nodes[i]).attr("color");
        shapes[i].attr({ fill:color, stroke:color, "fill-opacity":0.8, "stroke-width":2, cursor:"move"});
        shapes[i].id = "shapes_" + $(nodes[i]).attr("id");
        //shapes[i].drag(move, dragger, up); 去掉拖拽
        //让rect的next值与div中next值一致，便于作图
        shapes[i].next = $(nodes[i]).attr("next");
    }

    //根据每个节点的next值，连接相关联节点
    for (var i = 0; i < shapes.length; i++) {
        if (typeof(shapes[i].next) == "object") {
            break;
        }
        var childID = shapes[i].next.split(",");
        for (var j = 0; j < childID.length; j++) {
            var endPoint;
            //查找该rect的next值对应的rect
            for (var k = 0; k < shapes.length; k++) {
                if (shapes[k].id == "shapes_" + childID[j]) {
                    endPoint = shapes[k];
                }
            }
            connections.push(r.connection(shapes[i], endPoint));
        }
    }
    if (status == 'Suspended') {
        $("#"+svgContainer).prepend("<div class=\"gBlock\" style=\"height: 530px;" +
            "background: none repeat scroll 0% 0% white; position: relative; " +
            "margin-bottom: -530px; z-index: 9300; left: 0px; opacity: 0.5;\"></div>");
    }
}

/**
 * 画流程图，及对工作流的操作：暂停、恢复、终止、重启、步骤重启，
 * 另，工作流步骤提示信息也在此加载
 * @param url请求地址其中@mainWorkflowStep：【previewTranscode：转码-预览流】【uncatalogTranscode：非编转码】
 *                                           【operationalPush：运营推送】【programPublish：节目发布】
 *                                           【programRebuild：节目再制作】
 * @param divContainer  流程图上div容器ID
 * @param svgContainer  流程图上svg容器ID
 * @param leftOffset    div的偏移量
 * @param topOffset
 */

function chartWorkFlow(url,divContainer,svgContainer,leftOffset,topOffset,global) {
    jQuery.ajax({
        url:url + '&t=' + new Date().getTime(),
        type:"POST",
        global:global != null ? global : false,
        success:function (subWorkflow) {
            var stepInfos = subWorkflow.stepInfoList;
            var workflowId = subWorkflow.workflowId;
            var status = subWorkflow.status;
            var divHtml = "";
            var rightButtonHtml = "";
            if (stepInfos != undefined) {
                for (var i = 0; i < stepInfos.length; i++) {
                    if (stepInfos[i].stepId == 0) {
                        var firstStepDiv = "<div class=\"startpoint\" color=\"" + stepInfos[i].color + "\" begin=\"-1\"" +
                            " id=\"0\" next=\"" + stepInfos[i].nextStepIds + "\">开始</div>";
                        divHtml += firstStepDiv;
                    } else if (stepInfos[i].stepId == 999) {
                        var endStepDiv = "<div class=\"startpoint\" color=\""+stepInfos[i].color+"\" id=\"999\" " +
                            "\ next=\"-1\" >结束</div>";
                        divHtml += endStepDiv;
                    } else {
                        var middleStepDiv = "<div class=\"before\" color=\"" + stepInfos[i].color + "\" id=\"" + stepInfos[i].stepId +
                            "\" next=\"" + stepInfos[i].nextStepIds + "\" taskid=\"" + stepInfos[i].taskId + "\""+
                            " status=\"" + stepInfos[i].status + "\">" + stepInfos[i].stepName + "</div>";
                        divHtml += middleStepDiv;
                    }
                }
            }
            //工作流的操作：暂停、恢复、终止、重启
            if ($("#mainWorkflowStep").val() != 'catalog') {
                if (status == 'Finished') {

                } else if (status == 'Killed') {
                    rightButtonHtml +=
                        "&nbsp;&nbsp;<img src=\"" + ctx + "/img/workflow/restart.png\" onclick='restartWorkflow(" + workflowId + ");stopBubble(event)'/> 重启";
                } else if (status == 'Underway') {
                    rightButtonHtml +=
                        "&nbsp;&nbsp;<img  src=\"" + ctx + "/img/workflow/stop.png\" onclick='termWorkflow(" + workflowId + ");stopBubble(event)'>终止&nbsp;&nbsp;" +
                            "<img id=\"pause\" src=\"" + ctx + "/img/workflow/zaiting.png\" onclick='pauseWorkflow(" + workflowId + ");stopBubble(event)'/> 暂停&nbsp;&nbsp;" +
                            "<img src=\"" + ctx + "/img/workflow/restart.png\" onclick='restartWorkflow(" + workflowId + ");stopBubble(event)'/> 重启";
                } else if (status == 'Suspended') {
                    rightButtonHtml +=
                        "&nbsp;&nbsp;<img src=\"" + ctx + "/img/workflow/stop.png\" onclick='termWorkflow(" + workflowId + ");stopBubble(event)' /> 终止&nbsp;&nbsp;" +
                            "<img src=\"" + ctx + "/img/workflow/huifu.png\" onclick='resumeWorkflow(" + workflowId + ");stopBubble(event)' /> 恢复&nbsp;&nbsp;" +
                            "<img src=\"" + ctx + "/img/workflow/restart.png\" onclick='restartWorkflow(" + workflowId + ");stopBubble(event)'/> 重启";
                }
            }
            $(".rightButton").html(rightButtonHtml);
            $("#"+divContainer).html(divHtml);
            $("#"+divContainer).attr("workflowstatus", status);
            //加载步骤提示信息
            showSubWorkStepTips(workflowId);
            drawRects(divContainer, svgContainer, status, leftOffset, topOffset);
        }
    });
}

function termWorkflow(workflowId) {
    top.Boxy.confirm("确认: 强制终止" + "<span style='color: red'>" + workflowId + "</span>", function () {
        operation(workflowId, "terminate");
    }, {title:"确认信息"});
    return false;
}

function restartWorkflow(workflowId) {
    top.Boxy.confirm("确认: 强制终止流程" + "<span style='color: red'>" + workflowId + "</span>" + "并重新启动！",
        function () {
            operation(workflowId, "restart");
        }, {title:"确认信息"});
    return false;
}

function pauseWorkflow(workflowId) {
    top.Boxy.confirm("确认: 暂停流程" + "<span style='color: red'>" + workflowId + "</span>"
        + "将造成所有正在运行任务的终止！", function () {
        operation(workflowId, "pause");
    }, {title:"确认信息"});
    return false;
}

function resumeWorkflow(workflowId) {
    top.Boxy.confirm("确认: 恢复流程" + "<span style='color: red'>" + workflowId + "</span>"
        + "将重新启动暂停前正在运行的所有任务！", function () {
        operation(workflowId, "resume");
    }, {title:"确认信息"});
    return false;
}

function restart(workflowId, stepId) {
    top.Boxy.confirm("确认重启步骤：<span style='color: red'>" + stepId + "</span>?", function () {
        stepRestart(workflowId, stepId);
    }, {title:"确认信息"});
    return false;
}

//实际操作
function stepRestart(workflowId, stepId) {
    jQuery.ajax({
        url:ctx + '/workflow/info/steprestart.action?id=' + workflowId + '&stepId=' + stepId + '&t=' + new Date().getTime(),
        type:"GET",
        success:function (data) {
            var ret = eval('(' + data + ')');
            if (ret.code == 'A00000') {
                loadWorkflowChartPage();
            }else{
                top.Boxy.alert(ret.message, null, {title:"提示信息"});
            }
        }
    });
}

//实际操作
function operation(workflowId, actionURL) {
    jQuery.ajax({
        url:ctx + '/workflow/info/' + actionURL + '.action?id=' + workflowId + '&t=' + new Date().getTime(),
        type:"GET",
        success:function (data) {
            var ret = eval('(' + data + ')');
            if (ret.code == 'A00000') {
                //无select
                if ($("#businessSelect select").length == 0) {
                    //重启跳到最新工作流
                    if (actionURL == 'restart') {
                        jQuery.ajax({
                            url:ctx + '/workflow/workflowChart/getLatestWorkflowId.action?workflowId=' + workflowId,
                            type:"GET",
                            success:function (data) {
                                $("#entryId").attr("value",data.latestWorkflowId);
                                location.href = ctx + "/workflow/task/workflow-task.action?filter_EQL_workflowId="
                                    + data.latestWorkflowId + "&entryId=" + data.latestWorkflowId;
                            }
                        });

                    }else{
                        loadWorkflowChartPage();
                    }
                //节目发布、节目制作
                }else{
                    loadWorkflowChartPage();
                }
            }else{
                top.Boxy.alert(ret.message, null, {title:"提示信息"});
            }
        }
    });
}

//阻止冒泡事件
function stopBubble(e) {
    if (e && e.stopPropagation) {//非IE
        e.stopPropagation();
    }else {//IE
        window.event.cancelBubble = true;
    }
}

//在div上增加提示信息
function showSubWorkStepTips(workflowId) {
    var nodes = $("#spanBefore div");
    for (var i = 0; i < nodes.length; i++) {
        var mainWorkflowStep = $("#mainWorkflowStep").val();
        var transId = $("#transId").val();
        var workTaskId = $(nodes[i]).attr("taskId");
        var status = $(nodes[i]).attr("status");
        if (workTaskId != null && workTaskId != 'null' && workTaskId != undefined) {
            $(nodes[i]).poshytip({
                showOn:'hover',
                timeOnScreen:0,
                className:'tip-green',
                alignTo:'target',
                offsetY:0,
                offsetX:0,
                alignX:'inner-left',
                alignY:'bottom',
                allowTipHover:true,
                showTimeout:10,
                hideTimeout:100,
                fade: false,
                slide: false,
                slideOffset: 0,
                showAniDuration: 0,
                hideAniDuration: 0,
                content:function (updateCallback) {
                    var contents = null;
                    $.ajax({
                        type:'POST',
                        async:false,
                        global: false,
                        url:ctx + "/workflow/workflowChart/getSubWorkflowStepTips.action",
                        data:{workflowId:workflowId,
                            'workTaskId':$(this).attr("taskId"),
                            'transId':transId,
                            'status':$(this).attr("status"),
                            'materialName':$("#workflowSelect option:selected").text(),
                            'mainWorkflowStep':mainWorkflowStep,
                            't':new Date().getTime()
                        },
                        cache: false,
                        success:function (data) {
                            var tips = "<table>";
                            tips += "<tr><td width='68px'>开始时间 ：</td><td>" + trimNullOrUndefined(data.startTime) + "</td></tr>"
                                  + "<tr><td width='68px'>结束时间 ：</td><td>" + trimNullOrUndefined(data.endTime) + "</td></tr>"
                            if (data.operateProgress != null && data.transcodeFile != 'null' && data.transcodeFile != undefined) {
                                tips += "<tr><td width='68px'>转码文件 ：</td><td>" + data.transcodeFile + "</td></tr>";
                            }
                            if(data.videoSubtitleCount != null && data.videoSubtitleCount !='null'&& data.videoSubtitleCount != undefined){
                                tips += "<tr><td width='68px'>字幕文件 ：</td><td>" + data.videoSubtitleCount + "</td></tr>";
                            }
                            if (data.operateProgress != null && data.operateProgress != 'null' && data.operateProgress != undefined) {
                                tips += "<tr><td width='68px'>处理进度 ：</td><td>" + data.operateProgress + "%</td></tr>";

                            }
                            if (data.isSendAudit != null && data.isSendAudit != 'null' && data.isSendAudit != undefined) {
                                var auditInfo = trimNullOrUndefined(data.isSendAudit) == '1'?"已发送审核消息":"未发送审核消息"
                                tips += "<tr><td width='68px'>审核状况 ：</td><td>" + auditInfo+ "</td></tr>";

                            }
                            if (data.logInfo != null && data.logInfo != 'null' && data.logInfo != undefined) {
                                tips += "<tr><td width='68px'>日志信息 ：</td><td>" + trimNullOrUndefined(data.logInfo) + "</td></tr>";

                            }

                            if (mainWorkflowStep == 'catalog') {
                                tips += "<tr><td><a href=\"javascript:redirectCatalog(" + transId + ")\"> 由此进入编目 </a></td></tr>";
                            }
                            //步骤失败和进行状态可以重启,但编目不让重启。工作流暂停步骤不能重启
                            if (mainWorkflowStep != 'catalog') {
                                if (data.workflowStatus != 'Suspended' && data.workflowStatus != 'Killed') {
                                    if (data.status == 'Failed' || data.status == 'Underway') {
                                        tips += "<tr><td><div style=''>" +
                                            "<a style='text-align:center;background: #89B4CA;" +
                                            "color:white;cursor:pointer;padding: 0 4px 1px' " +
                                            "onclick='restart(" + workflowId + "," + data.stepId + ")'>" +
                                            "步骤重启</a></div></td></tr>"
                                    }
                                }
                            }
                            contents = tips + "</table>";
                        }
                    });
                    return contents;
                }
            });
        }else{
            //终止的步骤无任务的提示信息，排除999
            if($(nodes[i]).attr("color") == 'red' && $(nodes[i]).attr("id") != 999){
                $(nodes[i]).poshytip({
                    showOn:'hover',
                    className:'tip-green',
                    alignTo:'target',
                    offsetY:0,
                    offsetX:0,
                    alignX:'inner-left',
                    alignY:'bottom',
                    allowTipHover:true,
                    showTimeout:10,
                    hideTimeout:100,
                    fade: false,
                    slide: false,
                    slideOffset: 0,
                    showAniDuration: 0,
                    hideAniDuration: 0,
                    content:'开始时间：<br>结束时间：<br>日志信息：任务还未开始，步骤已经被暂停！'
                });
            }
        }
    }
}

function trimNullOrUndefined(sourceString) {
    if (sourceString == null || sourceString == 'null' || sourceString == undefined) {
        return "";
    } else {
        return  sourceString;
    }
}




